package base

import (
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"hosptial-record/global"
	"hosptial-record/global/response"
	"net/http"
	"strconv"
	"strings"
)

// GetID2Param 获取param中的ID
func GetID2Param(ctx *gin.Context) (id int32, err error) {
	str := ctx.Param("id")
	var i int
	i, err = strconv.Atoi(str)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, response.BaseResponse{
			Msg: "传入的ID不合法",
		})
		return id, err
	}
	id = int32(i)
	return id, err
}
func HandleGrpcErrorToHttp(err error, c *gin.Context) {
	if err != nil {
		if e, ok := status.FromError(err); ok {
			switch e.Code() {
			case codes.NotFound:
				c.JSON(http.StatusNotFound, response.BaseResponse{
					Msg: e.Message(),
				})
			case codes.Internal:
				c.JSON(http.StatusInternalServerError, response.BaseResponse{
					Msg: "内部错误",
				})
			case codes.InvalidArgument:
				c.JSON(http.StatusBadRequest, response.BaseResponse{
					Msg: "参数错误",
				})
			case codes.Unavailable:
				c.JSON(http.StatusInternalServerError, response.BaseResponse{
					Msg: "用户服务不可用",
				})
			default:
				c.JSON(http.StatusInternalServerError, response.BaseResponse{
					Msg: "其他错误",
				})
			}
		}
	}
	return
}

func RemoveTopStruct(fields map[string]string) map[string]string {
	rsp := map[string]string{}
	for field, err := range fields {
		key := strings.Split(field, ".")[1]
		rsp[key] = err
	}
	return rsp
}

func HandleValidatorError(ctx *gin.Context, err error) {
	var errs validator.ValidationErrors
	ok := errors.As(err, &errs)
	if !ok {
		ctx.JSON(http.StatusOK, response.BaseResponse{
			Msg: err.Error(),
		})
		return
	}
	ctx.JSON(http.StatusBadRequest, gin.H{
		"error": RemoveTopStruct(errs.Translate(global.Trans)),
	})
}
